import axios, { type Method } from 'axios'
import { getLocalToken } from './auth'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  (config) => {
    const token = getLocalToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)
type Data<T> = {
  code: number
  data: T
  message: string
}
//二次封装 request
const request = <T>(url: string, method: Method = 'GET', submitObj: object) => {
  return service.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitObj,
  })
}

export { request }
